package com.ruyuan.payment.server.service;

import com.ruyuan.payment.server.domain.User;
import com.ruyuan.payment.server.domain.UserExample;
import com.ruyuan.payment.server.exception.BusinessException;
import com.ruyuan.payment.server.exception.BusinessExceptionEnum;
import com.ruyuan.payment.server.mapper.UserMapper;
import com.ruyuan.payment.server.req.UserLoginReq;
import com.ruyuan.payment.server.resp.UserLoginResp;
import com.ruyuan.payment.server.util.CopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {
    private static final Logger LOG = LoggerFactory.getLogger(UserService.class);

    @Resource
    private UserMapper userMapper;

    public UserLoginResp login(UserLoginReq req) {
        // 校验登录名是否存在
        String loginName = req.getLoginName();
        UserExample userExample = new UserExample();
        userExample.createCriteria().andLoginNameEqualTo(loginName);
        List<User> list = userMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(list)) {
            LOG.info("登录名不存在，登录名：{}", loginName);
            throw new BusinessException(BusinessExceptionEnum.USER_LOGIN_ERROR);
        }
        User user = list.get(0);

        // 校验密码
        if (req.getPassword().equals(user.getPassword())) {
            // 登录成功
            return CopyUtil.copy(user, UserLoginResp.class);
        } else {
            // 登录失败
            LOG.info("密码错误，登录名：{}", loginName);
            throw new BusinessException(BusinessExceptionEnum.USER_LOGIN_ERROR);
        }

    }

}
